package com.inter.controller.paynotify;

import com.inter.entity.common.OrderPaymentManager;
import com.inter.entity.common.WXNotificationpaymentResults;
import com.inter.entity.pojo.Constant;
import com.inter.service.NotificationpaymentService;
import com.inter.service.OrderPaymentManagerService;
import com.inter.utils.pay.WxPayUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.util.Map;

@Controller
public class WeiXinPayH5NotifyController {
    @Autowired
    private OrderPaymentManagerService orderPaymentManagerService;
    @Autowired
    private NotificationpaymentService notificationpaymentService;
    //支付方式：1-公众号支付，2-paypal，3-oceanpay，4-H5微信支付，5，微信APP支付
    private String payType = "4";
    private static Logger logger = Logger.getLogger(WeiXinPayH5NotifyController.class);

    /**
     * 微信H5支付结果回调
     *
     * @param request
     * @param
     * @return
     */
    @RequestMapping(value = "/wxH5Notify")
    @CrossOrigin
    public String notify(HttpServletRequest request, HttpServletResponse response) {
        try {
            logger.info("H5微信支付回调获取数据开始");
            Map rMap = WxPayUtil.getH5NotifyResult(request);
            logger.info("H5微信支付回调notify获取的数据：" + rMap.get("resXml") + "");
            // 向微信输出处理结果，如果成功（SUCCESS），微信就不会继续调用了，否则微信会连续调用8次
            logger.info("开始分析H5微信回调数据:");
            String resXml = rMap.get("resXml") + "";
            String orderId = rMap.get("out_trade_no") + "";
            String result_code = rMap.get("result_code") + "";
            String return_code = rMap.get("return_code") + "";

            //为了从微信拿回来的金额能够直接使用
            String total_fee = rMap.get("total_fee") + "";
            int fee=Integer.parseInt(total_fee)/100;
            String payAmount = Integer.toString(fee);

            String appid = rMap.get("appid") + "";
            String bank_type = rMap.get("bank_type") + "";
            String cash_fee = rMap.get("cash_fee") + "";
            String fee_type = rMap.get("fee_type") + "";
            String is_subscribe = rMap.get("is_subscribe") + "";
            String mch_id = rMap.get("mch_id") + "";
            String nonce_str = rMap.get("nonce_str") + "";
            String openid = rMap.get("openid") + "";
            String out_trade_no = rMap.get("out_trade_no") + "";
            String sign = rMap.get("sign") + "";
            String time_end = rMap.get("time_end") + "";
            String trade_type = rMap.get("trade_type") + "";
            String transaction_id = rMap.get("transaction_id") + "";

            //去数据库查询out_trade_no是不是已经入过库
            int count = notificationpaymentService.findCountByOutTradeno(out_trade_no);
            if (count <= 0) {
                //将微信回传的交易记录入库保存下来
                WXNotificationpaymentResults results = new WXNotificationpaymentResults();
                results.setAppid(appid);
                results.setBankType(bank_type);
                results.setCashFee(cash_fee);
                results.setFeeType(fee_type);
                results.setIsSubscribe(is_subscribe);
                results.setMchId(mch_id);
                results.setNonceStr(nonce_str);
                results.setOpenid(openid);
                results.setOutTradeNo(out_trade_no);
                results.setResultCode(result_code);
                results.setReturnCode(return_code);
                results.setSign(sign);
                results.setTimeEnd(time_end);
                results.setTotalFee(total_fee);
                results.setTradeType(trade_type);
                results.setTransactionId(transaction_id);
                notificationpaymentService.insertPaymentResults(results);
            }

            // 判断result_code和return_code同时是SUCCESS就return给北京
            if (result_code.equalsIgnoreCase("SUCCESS") || return_code.equalsIgnoreCase("SUCCESS")) {
                // 查询一下当前out_trade_no单号有没有通知过北京，要是通知过IsNotify肯定是0了，
                //根据微信回调的订单号去数据库查询当前记录是不是已经记录
                System.out.println("回调的支付订单号out_trade_no：" + orderId);
                int c = orderPaymentManagerService.findOrderIdByNotify(orderId);
                if (c <= 0) {
                    OrderPaymentManager paymentOrder = new OrderPaymentManager();
                    // 成功就将PayRst设为1；不插入就数据库默认0
                    // 成功就要通知，数据库就记1，不成功就不通知数据库会默认0
                    paymentOrder.setPayRst("success");
                    paymentOrder.setIsNotify("1");
                    paymentOrder.setOrderId(out_trade_no);
                    paymentOrder.setPayType( Constant.PAY_WeChatH5);
                    orderPaymentManagerService.updatePayRst(paymentOrder);
                    System.out.println("支付结果入库完成！");
                    //拿到orderId就去做支付结果通知就好
                    return "forward:/payNotify?orderId=" + orderId + "&payType=" + Constant.PAY_WeChatH5 + "&payAmount=" + payAmount + "";
                }

            }
            //回复微信说：你不要在发信息给我，我收到了
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            out.write(resXml.getBytes());
            out.flush();
            out.close();
//            response.setContentType("text/html");
//            response.setCharacterEncoding("UTF-8");
//            response.getWriter().println("SUCCESS");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
